package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
@Component
public class GlobalExeptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerException(SQLIntegrityConstraintViolationException e){
        // 1、打印异常信息 log.error()  getMessage
        e.printStackTrace();
        // 2、获取异常信息 getMessage()  Duplicate entry '111' for key 'idx_username'
        String message = e.getMessage();
        String[] split = message.split("'");
        return R.error("账号"+split[1]+"已存在");
        // 3、判断异常信息是唯一约束异常  contains("Duplicate entry")
        //if(message.contains("Duplicate entry")){//违反的是唯一约束
            //3.1、如果是，获取异常信息中的用户名 split  replace ，返回 xxx已存在
            //3.2、如果不是，返回 “数据异常！！”
    }

    //处理我们的自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public R handlerBusinessException(BusinessException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
